package com.yunhe.common.i18n;

import com.yunhe.common.util.ChineseCharUtil;
import com.yunhe.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * I18n工具类
 * @author duanxiaoyong
 */
public class I18nMessageUtil {

    private static final Logger logger = LoggerFactory.getLogger(I18nMessageUtil.class);

    private static final String PATH_PARENT = "classpath:i18n/";
    private static final String SUFFIX = ".properties";
    private static ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    private static Map<String, String> chineseCharMap = new ConcurrentHashMap<>();
    private static Map<String, MessageSourceAccessor> accessorMap = new ConcurrentHashMap<>();
    private static Map<String, Locale> localeMap = new ConcurrentHashMap<>();
    private static final String[] MONTH = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    private static final String EN = "en";
    private static final String ZH = "zh";

    public static synchronized void init() throws IOException {
        Resource resource = resourcePatternResolver.getResource(PATH_PARENT + "en_us" + SUFFIX);
        BufferedReader br = new BufferedReader(new FileReader(resource.getFile()));
        String str;
        while ((str = br.readLine()) != null) {
            if (!str.startsWith("#") && !StringUtil.isEmpty(str)) {
                String[] split = str.split("=");
                chineseCharMap.put(split[0], split[1]);
            }
        }
        br.close();
    }

    private I18nMessageUtil() {
    }

    /**
     * 初始化资源文件的存储器
     * 加载指定语言配置文件
     *
     * @param language 语言类型(文件名即为语言类型,eg: en_us 表明使用 美式英文 语言配置)
     */
    private static synchronized MessageSourceAccessor initMessageSourceAccessor(String language) {
        if (accessorMap.get(language) != null) {
            return accessorMap.get(language);
        }
        try {
            /**
             * 获取配置文件名
             */
            Resource resource = resourcePatternResolver.getResource(PATH_PARENT + language + SUFFIX);
            String fileName = resource.getURL().toString();
            int lastIndex = fileName.lastIndexOf(".");
            String baseName = fileName.substring(0, lastIndex);
            /**
             * 读取配置文件
             */
            ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
            reloadableResourceBundleMessageSource.setBasename(baseName);
            reloadableResourceBundleMessageSource.setCacheSeconds(5);
            reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8");
            MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(reloadableResourceBundleMessageSource);
            accessorMap.put(language, messageSourceAccessor);
            return messageSourceAccessor;
        } catch (FileNotFoundException ignored) {
            //忽略没有配置翻译文件的错误
        } catch (Exception e) {
            logger.error("i18读取文件错误", e);
        }
        return null;
    }

    /**
     * 获取一条语言配置信息
     *
     * @param language       语言类型,zh_cn: 简体中文, en_us: 英文
     * @param message        配置信息属性名,eg: api.response.code.user.signUp
     * @param defaultMessage 默认信息,当无法从配置文件中读取到对应的配置信息时返回改信息
     * @return
     * @throws IOException
     */
    public static String getMessage(String language, String message, String defaultMessage) {
        if (StringUtil.isEmpty(message)) {
            return message;
        }
        if (language == null) {
            language = ZH;
        }
        if (ZH.equals(language)) {
            message = message.replace(" ", "");
        }
        MessageSourceAccessor accessor = initMessageSourceAccessor(language);
        if (accessor == null) {
            return message;
        }
        String msg;
        if (localeMap.get(language) != null) {
            Locale locale = localeMap.get(language);
            msg = accessor.getMessage(message, defaultMessage, locale);
        } else {
            Locale locale = new Locale(language);
            localeMap.put(language, locale);
            msg = accessor.getMessage(message, defaultMessage, locale);
        }
        return msg;
    }

    public static String getMessage(String language, String message) {
        return getMessage(language, message, message);
    }

    public static String getMessage(String message) {
        return getMessage(LanguageHolder.getLanguage(), message, message);
    }

    /**
     * 获取组合信息
     * @param language
     * @param originalMsg
     * @return
     */
    public static String getMessageGroup(String language, String originalMsg) {
        if (ZH.equals(language)) {
            originalMsg = originalMsg.replace(" ", "");
        }
        if (originalMsg != null) {
            List<String> list = ChineseCharUtil.match(originalMsg);
            for (String s : list) {
                originalMsg = originalMsg.replaceFirst(s, getMessage(language, s));
            }
            return originalMsg;
        } else {
            return null;
        }
    }

    public static String getGroupMessage(String originalMsg) {
        try {
            if (chineseCharMap.size() == 0) {
                init();
            }
            String str;
            while ((str = getContainsMapKey(originalMsg, chineseCharMap)) != null) {
                originalMsg = originalMsg.replaceFirst(str, chineseCharMap.get(str));
            }
        } catch (Exception e) {}
        return originalMsg;
    }

    public static String getContainsMapKey(String str, Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            if (str.contains(key)) {
                return key;
            }
        }
        return null;
    }

    public static String getCustomMessage(String language, String originalMsg) {
        if (ZH.equals(language)) {
            originalMsg = originalMsg.replace(" ", "");
            originalMsg = getMessage(language, originalMsg, originalMsg);
        }
        if (EN.equals(language)) {
            if (originalMsg.contains("在") && originalMsg.contains("页面进行了") && originalMsg.contains("操作")) {
                String userTitle = originalMsg.substring(0, originalMsg.indexOf("在"));
                String page = originalMsg.substring(originalMsg.indexOf("在") + 1, originalMsg.indexOf("页面进行了"));
                if (page.endsWith("报表")) {
                    page = page.replace("报表", "");
                }
                page = getMessage(EN, page);
                String action = originalMsg.substring(originalMsg.indexOf("页面进行了") + 5, originalMsg.indexOf("操作"));
                if (action.contains("差异原因分析记录")) {
                    action = action.replace("差异原因分析记录", "");
                }
                action = getMessage(EN, action);
                originalMsg = userTitle + " did " + action + " operation in " + page;
            } else if (originalMsg.contains("在") && originalMsg.contains("进行了") && originalMsg.contains("操作")) {
                String userTitle = originalMsg.substring(0, originalMsg.indexOf("在"));
                String page = originalMsg.substring(originalMsg.indexOf("在") + 1, originalMsg.indexOf("进行了"));
                if (page.endsWith("报表")) {
                    page = page.replace("报表", "");
                }
                page = getMessage(EN, page);
                String action = originalMsg.substring(originalMsg.indexOf("进行了") + 5, originalMsg.indexOf("操作"));
                if (action.contains("差异原因分析记录")) {
                    action.replace("差异原因分析记录", "");
                }
                action = getMessage(EN, action);
                originalMsg = userTitle + " did " + action + " operation in " + page;
            } else if (originalMsg.contains("在") && originalMsg.contains("把") && originalMsg.contains("的启用状态设置为")) {
                String userTitle = originalMsg.substring(0, originalMsg.indexOf("在"));
                String strategyTitle = originalMsg.substring(originalMsg.indexOf("把") + 1, originalMsg.indexOf("的启用状态设置为"));
                String status = originalMsg.substring(originalMsg.indexOf("的启用状态设置为") + 8);
                status = status.replace("“", "Disenable");
                String action = "启用".equals(status) ? "Enable" : "Disenable";
                originalMsg = userTitle + " " + action +" " + strategyTitle + " in Strategy Management";
            } else if (originalMsg.startsWith("储能电站") && originalMsg.contains("发生") && originalMsg.endsWith("告警")) {
                String devTitle = originalMsg.substring(originalMsg.indexOf("储能电站") + 4, originalMsg.indexOf("发生"));
                devTitle = getMessage(EN, devTitle);
                String alarmTitle = originalMsg.substring(originalMsg.indexOf("发生") + 2, originalMsg.indexOf("告警"));
                alarmTitle = getMessage(EN, alarmTitle);
                originalMsg = "ESS " + devTitle + " occurred the " + alarmTitle + " Alarm";
            } else if (originalMsg.contains("导出了")) {
                originalMsg = "Operator:" + originalMsg;
                originalMsg = originalMsg.replaceFirst("导出了", ";Operate:export ");
            } else if (originalMsg.contains("放电功率变化为") && originalMsg.contains("上次放电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("放电功率变化为"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("放电功率变化为") + 7, originalMsg.indexOf("kW，上次放电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("上次放电功率") + 6);
                originalMsg = devTitle + " Discharge Power Change to " + nowPower + "kW,and the last Discharge Power was " + lastPower;
            } else if (originalMsg.contains("放电功率变化为") && originalMsg.contains("设定放电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("放电功率变化为"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("放电功率变化为") + 7, originalMsg.indexOf("kW，设定放电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("设定放电功率") + 6);
                originalMsg = devTitle + " Discharge Power Change was " + nowPower + "kW,and the Discharge Power was set to " + lastPower;
            } else if (originalMsg.contains("开始放电") && originalMsg.contains("设定放电功率") && originalMsg.contains("实际开始放电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("开始放电"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("设定放电功率") + 6, originalMsg.indexOf("kW，实际开始放电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("实际开始放电功率") + 8);
                originalMsg = devTitle + " starts to discharge, the Discharge Power was set to " + nowPower + "kW, and Actual Initial Discharge Power is " + lastPower;
            } else if (originalMsg.contains("充电功率变化为") && originalMsg.contains("上次充电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("充电功率变化为"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("充电功率变化为") + 7, originalMsg.indexOf("kW，上次充电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("上次充电功率") + 6);
                originalMsg = devTitle + " Charge Power Change to " + nowPower + "kW,and the last Charge Power was " + lastPower;
            } else if (originalMsg.contains("充电功率变化为") && originalMsg.contains("设定充电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("充电功率变化为"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("充电功率变化为") + 7, originalMsg.indexOf("kW，设定充电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("设定充电功率") + 6);
                originalMsg = devTitle + " Charge Power Change was " + nowPower + "kW,and the Charge Power was set to " + lastPower;
            } else if (originalMsg.contains("开始充电") && originalMsg.contains("设定充电功率") && originalMsg.contains("实际开始充电功率")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("开始充电"));
                devTitle = getMessage(EN, devTitle);
                String nowPower = originalMsg.substring(originalMsg.indexOf("设定充电功率") + 6, originalMsg.indexOf("kW，实际开始充电功率"));
                String lastPower = originalMsg.substring(originalMsg.indexOf("实际开始充电功率") + 8);
                originalMsg = devTitle + " starts to charge, the charge Power was set to " + nowPower + "kW, and Actual Initial Charge Power is " + lastPower;
            } else if (originalMsg.contains("SOC已经上升到") && originalMsg.contains("当前正在充电，充电功率为") && originalMsg.contains("预计充到") && originalMsg.contains("还有")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("SOC已经上升到"));
                devTitle = getMessage(EN, devTitle);
                String nowSoc = originalMsg.substring(originalMsg.indexOf("SOC已经上升到") + 8, originalMsg.indexOf("%，当前正在充电"));
                String nowPower = originalMsg.substring(originalMsg.indexOf("当前正在充电，充电功率为") + 12, originalMsg.indexOf("kW，预计充到"));
                String targetSoc = originalMsg.substring(originalMsg.indexOf("预计充到") + 4, originalMsg.indexOf("%，还有"));
                String time = originalMsg.substring(originalMsg.indexOf("还有") + 2);
                time = time.replace("小时", "h");
                time = time.replace("分钟", "min");
                time = time.replace("分", "min");
                time = time.replace("秒", "s");
                originalMsg = "The SOC of " + devTitle + " rise to " + nowSoc + "%, there still " + time + " charge to " + targetSoc +"%, and the Charge Power is " + nowPower + "kW.";
            } else if (originalMsg.contains("SOC已经下降到") && originalMsg.contains("当前正在放电，放电功率为") && originalMsg.contains("预计放到") && originalMsg.contains("还有")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("SOC已经下降到"));
                String nowSoc = originalMsg.substring(originalMsg.indexOf("SOC已经上升到") + 8, originalMsg.indexOf("%，当前正在放电"));
                String nowPower = originalMsg.substring(originalMsg.indexOf("当前正在放电，放电功率为") + 12, originalMsg.indexOf("kW，预计放到"));
                String targetSoc = originalMsg.substring(originalMsg.indexOf("预计放到") + 4, originalMsg.indexOf("%，还有"));
                String time = originalMsg.substring(originalMsg.indexOf("还有") + 2);
                time = time.replace("小时", "h");
                time = time.replace("分钟", "min");
                time = time.replace("分", "min");
                time = time.replace("秒", "s");
                originalMsg = "The SOC of " + devTitle + " drop to " + nowSoc + "%,there still " + time + " discharge to " + targetSoc + "%, and the Discharge Power is " + nowPower + "kW";
            } else if (originalMsg.endsWith("进入待机状态")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("进入待机状态"));
                devTitle = getMessage(EN, devTitle);
                originalMsg = devTitle + " change to standby state";
            } else if (originalMsg.endsWith("进入故障状态")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("进入故障状态"));
                devTitle = getMessage(EN, devTitle);
                originalMsg = devTitle + " change to failure state";
            }  else if (originalMsg.endsWith("进入蓄电状态")) {
                String devTitle = originalMsg.substring(0, originalMsg.indexOf("进入蓄电状态"));
                devTitle = getMessage(EN, devTitle);
                originalMsg = devTitle + " change to accumulator state";
            } else if (originalMsg.startsWith("储能电站") && originalMsg.contains("自动消除，持续")) {
                String devTitle = originalMsg.substring(originalMsg.indexOf("储能电站") + 4, originalMsg.indexOf("在"));
                devTitle = getMessage(EN, devTitle);
                String startTime = originalMsg.substring(originalMsg.indexOf("在") + 1, originalMsg.indexOf("发生的"));
                String alarmTitle = originalMsg.substring(originalMsg.indexOf("发生的") + 3, originalMsg.indexOf("告警"));
                alarmTitle = getMessage(EN, alarmTitle);
                String endTime = originalMsg.substring(originalMsg.indexOf("已于") + 2, originalMsg.indexOf("自动消除"));
                String continueTime = originalMsg.substring(originalMsg.indexOf("持续") + 2);
                originalMsg = "The " + alarmTitle + " Alarm occurred in " + devTitle + " at " + startTime + "," +
                        "was eliminated automatically at "  + endTime +", it lasts " + continueTime;
            } else if (originalMsg.startsWith("储能电站") && originalMsg.contains("处理，处理人")) {
                String devTitle = originalMsg.substring(originalMsg.indexOf("储能电站") + 4, originalMsg.indexOf("在"));
                devTitle = getMessage(EN, devTitle);
                String startTime = originalMsg.substring(originalMsg.indexOf("在") + 1, originalMsg.indexOf("发生的"));
                String alarmTitle = originalMsg.substring(originalMsg.indexOf("发生的") + 3, originalMsg.indexOf("告警"));
                alarmTitle = getMessage(EN, alarmTitle);
                String endTime = originalMsg.substring(originalMsg.indexOf("已于") + 2, originalMsg.indexOf("处理"));
                String name = originalMsg.substring(originalMsg.indexOf("处理人为") + 4);
                originalMsg = "The " + alarmTitle + " Alarm occurred in " + devTitle + " at " + startTime + ",was handled by " + name + " at " + endTime;
            } else if (originalMsg.contains("当前值为") && originalMsg.contains("阈值为")) {
                String title = originalMsg.substring(originalMsg.indexOf("当前值为") + 4, originalMsg.indexOf(":"));
                title = getMessage(EN, title);
                String value = originalMsg.substring(originalMsg.indexOf(":"), originalMsg.indexOf("，"));
                String threshold = originalMsg.substring(originalMsg.indexOf("阈值为") + 3);
                originalMsg = "The current value is " + title + value + ", The threshold is " + threshold;
            } else if (originalMsg.startsWith("发生") && originalMsg.endsWith("事件")) {
                String title = originalMsg.substring(originalMsg.indexOf("发生") + 2, originalMsg.indexOf("事件"));
                title = getMessage(EN, title);
                originalMsg = title + " occurred";
            } else if (originalMsg.contains("年") && originalMsg.endsWith("月")) {
                originalMsg = originalMsg.replace("年", " ");
                originalMsg = originalMsg.replace("月", "");
                String[] split = originalMsg.split(" ");
                originalMsg = MONTH[Integer.parseInt(split[1]) - 1] + "." + split[0];
            } else if (originalMsg.startsWith("已存在名称为") && originalMsg.contains("的电站")) {
                originalMsg = "Station name exists in system";
            } else if (originalMsg.startsWith("已存在手机号")) {
                originalMsg = "The phone number already exists";
            }
            getGroupMessage(originalMsg);
        }
        return getMessageGroup(language, originalMsg);
    }

    public static String getMessageForShow(String msg, String language) throws IOException {
        if (ZH.equals(language)) {
            return msg;
        }
        String message = getMessage(language, msg, msg);
        if (message.equals(msg)) {
            String groupMessage = getGroupMessage(msg);
            if (groupMessage.equals(msg)) {
                return processMsgForShow(msg);
            } else {
                return groupMessage;
            }
        } else {
            return message;
        }
    }

    public static String processMsgForShow(String msg) {
        if (msg.endsWith("开关")) {
            msg = msg.replace("开关", " Breaker");
        } else if (msg.contains("变流器")) {
            msg = msg.replace("变流器", "PCS");
        } else if (msg.startsWith("第") && msg.endsWith("节单体电池")) {
            msg = msg.replace("第", "");
            msg = msg.replace("节单体电池", "#Cell ");
        } else if (msg.endsWith("电池组")) {
            msg = msg.replace("电池组", "BatteryCluster");
        } else if (msg.endsWith("单体电池电压")) {
            msg = "Voltage";
        } else if (msg.endsWith("单体电池温度")) {
            msg = "Temperature";
        } else if (msg.startsWith("BC#") && msg.endsWith("温度")) {
            msg = msg.replace("温度", " Temperature");
        } else if (msg.startsWith("BC#") && msg.endsWith("电压")) {
            msg = msg.replace("电压", " Voltage");
        } else if (msg.contains("_")) {
            if (ChineseCharUtil.match(msg).size() > 0) {
                msg = msg.substring(msg.indexOf("_") + 1);
                msg = getMessage(EN, msg);
            }
        }
        return msg;
    }

    public static String getAlarmMsg(String language, String records) {
        String messageGroup = getMessageGroup(language, records);
        if (EN.equals(language) && !StringUtil.isEmpty(records) && ChineseCharUtil.match(messageGroup).size() > 0) {

            if (records.contains("当前值为") && records.contains("阈值为") && records.contains(":")) {
                String title = records.substring(records.indexOf("当前值为") + 4, records.indexOf(":"));
                title = getMessage(EN, title);
                String value = records.substring(records.indexOf(":"), records.indexOf("，"));
                String threshold = records.substring(records.indexOf("阈值为") + 3);
                records = "The current value is " + title + value + ", The threshold is " + threshold;
                messageGroup = records;
            } else if (records.contains("当前值为") && records.contains("阈值为") && !records.contains(":")) {
                String title = records.substring(records.indexOf("当前值为") + 4, records.indexOf("，"));
                String threshold = records.substring(records.indexOf("阈值为") + 3);
                records = "The current value is " + title  + ", The threshold is " + threshold;
                messageGroup = records;
            } else if (records.contains("当前值为") && !records.contains("阈值为") && !records.contains(":")) {
                String title = records.substring(records.indexOf("当前值为") + 4, records.indexOf("，"));
                records = "The current value is " + title;
                messageGroup = records;
            } else if (records.startsWith("发生") && records.endsWith("事件") && records.length() > 2) {
                String title = records.substring(records.indexOf("发生") + 2, records.indexOf("事件"));
                title = getMessage(EN, title);
                records = title + " occurred";
                messageGroup = records;
            }
        }
        return messageGroup;
    }
}